﻿using System;
using System.Linq;
using Newtonsoft.Json;

namespace Ecobee.Net
{
	public class ApiTemperatureConverter : JsonConverter
	{
		private readonly Type[] _allowedTypes = new Type[] { typeof(Int16), typeof(Int32), typeof(Int64), typeof(Double), typeof(Single) };

		public override bool CanConvert(Type objectType)
		{
			bool returnValue = false;

			returnValue = _allowedTypes.Contains(objectType);

			return returnValue;
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			object returnValue = null;

			if (reader.ValueType == typeof(Int16) ||
				reader.ValueType == typeof(Int32) ||
				reader.ValueType == typeof(Int64))
			{
				// ***
				// *** The API returns -5002 for a null value
				// ***
				if ((long)reader.Value != -5002)
				{
					((ApiTemperature)existingValue).ThermostatTemperature = (long)reader.Value;
					returnValue = existingValue;
				}
			}
			else if (reader.ValueType == typeof(Single) ||
				reader.ValueType == typeof(Double))
			{
				// ***
				// *** The API returns -5002 for a null value
				// ***
				if ((long)reader.Value != -5002)
				{
					((ApiTemperature)existingValue).RealTemperature = (float)reader.Value;
					returnValue = existingValue;
				}
			}

			return returnValue;
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			writer.WriteValue(((ApiTemperature)value).ThermostatTemperature);
		}
	}
}
